package com.se.optionView;

import com.se.mainView.MainViewController;
import com.se.utils.ClientUtils;
import com.se.utils.FileChooserService;
import com.se.utils.ServiceUtils;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;

import javax.swing.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.*;
import java.util.stream.Stream;

import static com.se.utils.ServiceUtils.*;

public class OptionController implements Initializable {
    @FXML
    public ListView<String> navList;

    @FXML
    public StackPane contentPane;

    @FXML
    public Button btnConfirm;

    public Button btnChangePwd;

    public Button btnSetFilePath;
    public Label lblFilePath;
    public TextField tfKey;
    public ComboBox<String> AITypeComboBox;
    public ComboBox<String> modelComboBox;
    public ComboBox<Integer> maxDetectComboBox;
    public ToggleButton autoDetectToggle;

    private final Map<String, Node> viewMap = new HashMap<>();

    private String selectedItem;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        System.out.println("初始化设置界面");
        navList.setItems(FXCollections.observableArrayList("通用设置"));

        viewMap.put("通用设置", createAISettings());
        navList.getSelectionModel().selectedItemProperty().addListener(
                (obs, oldVal, newVal) -> {
                    showView(newVal);
                    selectedItem = newVal;
                });
        navList.getSelectionModel().selectFirst();
    }

    private void showView(String viewName) {
        contentPane.getChildren().setAll(viewMap.get(viewName));
    }

    @FXML
    public void btnConfirmOnClick() {
        if(selectedItem.equals("个人资料")) {
            /*
            修改用户信息逻辑待填充
            本地修改、服务器修改、所有用户同步
             */
        }
        else if (selectedItem.equals("通用设置")) {
            AITYPE = AITypeComboBox.getValue();
            APIKEY = tfKey.getText();
            MODEL = modelComboBox.getValue();
            MAX_DETECT_NUM = maxDetectComboBox.getValue();
            FILE_STORAGE_PATH = lblFilePath.getText();
            String storagePath = FILE_STORAGE_PATH.replace("\\", "\\\\");

            List<String> content = Arrays.asList(
                    "# 通用配置参数",
                    "AI-type=" + AITYPE,
                    "api-key=" + APIKEY,
                    "model=" + MODEL,
                    "auto_detect=" + AUTO_DETECT_TEXT,
                    "max_detect=" + MAX_DETECT_NUM,
                    "file_storage_path=" + storagePath
            );

            try {
                Files.write(ServiceUtils.getFilePath(), content,
                        StandardCharsets.UTF_8,
                        StandardOpenOption.TRUNCATE_EXISTING);
                ClientUtils.information_Alert("修改成功！");
                MainViewController.getInstance().refreshMessageList();
            } catch (IOException e) {
                /*
                异常处理待优化
                 */
                e.printStackTrace();
            }
        }
    }


    private Node createAISettings() {
        VBox panel = new VBox(20);
        AITypeComboBox = new ComboBox<>();
        modelComboBox = new ComboBox<>();
        tfKey = new TextField();
        maxDetectComboBox = new ComboBox<>();
        autoDetectToggle = new ToggleButton();
        Properties properties = new Properties();
        try(InputStream input = Files.newInputStream(ServiceUtils.getFilePath())) {
            properties.load(input);
            AITYPE = properties.getProperty("AI-type");
            APIKEY = properties.getProperty("api-key");
            MODEL = properties.getProperty("model");
            AUTO_DETECT_TEXT = Boolean.parseBoolean(properties.getProperty("auto_detect"));
            MAX_DETECT_NUM = Integer.parseInt(properties.getProperty("max_detect"));
            FILE_STORAGE_PATH = properties.getProperty("file_storage_path");

            ObservableList<String> AIList = FXCollections.observableArrayList(
                    "DeepSeek",
                    "OpenAI"
            );
            AITypeComboBox.setItems(AIList);

            //根据AI种类变化动态加载模型种类
            AITypeComboBox.valueProperty().addListener((obs, oldVal, newVal) -> {
                if(newVal.equals("DeepSeek")) {
                    ObservableList<String> modelList =
                            FXCollections.observableArrayList("deepseek-chat");
                    modelComboBox.setItems(modelList);
                    modelComboBox.getSelectionModel().selectFirst();
                }
                else {
                    ObservableList<String> modelList =
                            FXCollections.observableArrayList(
                                    "GPT-4",
                                    "GPT-3.5-turbo"
                            );
                    modelComboBox.setItems(modelList);
                }
            });

            if(AITYPE != null && !AITYPE.isEmpty()) {
                AITypeComboBox.setValue(AITYPE);
            }

            if(MODEL != null && !MODEL.isEmpty()) {
                modelComboBox.setValue(MODEL);
            }

            ObservableList<Integer> values = FXCollections.observableArrayList();
            for(int i = 5; i <= 15; i++) {
                values.add(i);
            }
            maxDetectComboBox.setItems(values);


            maxDetectComboBox.setValue(MAX_DETECT_NUM);

            autoDetectToggle.selectedProperty().addListener((obs, oldVal, newVal) -> {
                AUTO_DETECT_TEXT = newVal;
                String s;
                if(newVal) {
                    s = "开";
                }
                else{
                    s = "关";
                }
                autoDetectToggle.setText(s);
            });

            autoDetectToggle.setSelected(AUTO_DETECT_TEXT);
            if(AUTO_DETECT_TEXT) {
                autoDetectToggle.setText("开");
            }
            else {
                autoDetectToggle.setText("关");
            }

            lblFilePath = new Label(Objects.requireNonNullElse(FILE_STORAGE_PATH, "请设置文件存储路径"));
            btnSetFilePath = new Button("设置");
            btnSetFilePath.setOnAction(event -> new Thread(() -> {
               String path = FileChooserService.showChooseFileUI(JFileChooser.DIRECTORIES_ONLY, false);
               Platform.runLater(() -> lblFilePath.setText(path));
            }).start());

            Label labelA = new Label("AI种类:   ");
            Label labelB = new Label("API_KEY: ");
            Label labelC = new Label("模型种类:  ");
            Label labelD = new Label("自动检测文本: ");
            Label labelE = new Label("检测文本数量上限: ");
            Label labelF = new Label("文件存储路径: ");
            labelA.setMinWidth(80);
            labelB.setMinWidth(80);
            labelC.setMinWidth(80);
            labelD.setMinWidth(80);
            labelE.setMinWidth(80);
            labelF.setMinWidth(80);

            if(APIKEY != null && !APIKEY.isEmpty()) {
                tfKey.setText(APIKEY);
            }

            HBox line1 = new HBox(10, labelA, AITypeComboBox);
            HBox line2 = new HBox(10, labelB, tfKey);
            HBox line3 = new HBox(10, labelC, modelComboBox);
            HBox line4 = new HBox(10, labelD, autoDetectToggle);
            HBox line5 = new HBox(10, labelE, maxDetectComboBox);
            HBox line6 = new HBox(10, labelF, lblFilePath, btnSetFilePath);

            //统一设置对齐，AI写的
            Stream.of(line1, line2, line3, line4, line5, line6).forEach(hbox -> {
                hbox.setAlignment(Pos.CENTER_LEFT);
                HBox.setHgrow(hbox.getChildren().get(1), Priority.ALWAYS);
            });

            panel.getChildren().addAll(line1, line2, line3, line4, line5, line6);

        } catch (IOException e) {
            /*
            后续优化异常处理
             */
            e.printStackTrace();
        }

        return panel;
    }

    private Node createUserArchive() {
        VBox panel = new VBox(20);
        HBox line1 = new HBox(20);
        HBox line2 = new HBox(20);
        btnChangePwd = new Button("修改密码");
        line1.getChildren().addAll(
                new Label("用户名: "),
                new Label(ServiceUtils.getSpeaker().getUserName())
        );
        line2.getChildren().addAll(
                new Label("密码: "),
                new Label("*********")
        );
        panel.setPadding(new Insets(25));
        panel.getChildren().addAll(line1, line2, btnChangePwd);
        return panel;
    }
}
